package com.laundry.service;

import com.laundry.entity.User;
import com.laundry.entity.UserAddress;
import com.laundry.repository.UserAddressRepository;
import com.laundry.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class UserAddressService {
    
    private final UserAddressRepository addressRepository;
    private final UserRepository userRepository;
    
    public List<UserAddress> getUserAddresses() {
        User user = getCurrentUser();
        return addressRepository.findByUserOrderByIsDefaultDescCreatedAtDesc(user);
    }
    
    @Transactional
    public UserAddress addAddress(UserAddress address) {
        User user = getCurrentUser();
        address.setUser(user);
        
        // 如果是第一个地址，自动设为默认
        if (addressRepository.countByUser(user) == 0) {
            address.setIsDefault(true);
        }
        
        // 如果设置为默认地址，取消其他默认地址
        if (address.getIsDefault()) {
            addressRepository.findByUserAndIsDefaultTrue(user)
                    .ifPresent(defaultAddress -> {
                        defaultAddress.setIsDefault(false);
                        addressRepository.save(defaultAddress);
                    });
        }
        
        return addressRepository.save(address);
    }
    
    @Transactional
    public UserAddress updateAddress(Long id, UserAddress updatedAddress) {
        User user = getCurrentUser();
        UserAddress address = addressRepository.findByUserAndId(user, id)
                .orElseThrow(() -> new RuntimeException("地址不存在"));
        
        // 更新地址信息
        address.setContactName(updatedAddress.getContactName());
        address.setContactPhone(updatedAddress.getContactPhone());
        address.setProvince(updatedAddress.getProvince());
        address.setCity(updatedAddress.getCity());
        address.setDistrict(updatedAddress.getDistrict());
        address.setStreet(updatedAddress.getStreet());
        address.setDetailAddress(updatedAddress.getDetailAddress());
        address.setLatitude(updatedAddress.getLatitude());
        address.setLongitude(updatedAddress.getLongitude());
        address.setType(updatedAddress.getType());
        
        // 如果设置为默认地址，取消其他默认地址
        if (updatedAddress.getIsDefault() && !address.getIsDefault()) {
            addressRepository.findByUserAndIsDefaultTrue(user)
                    .ifPresent(defaultAddress -> {
                        defaultAddress.setIsDefault(false);
                        addressRepository.save(defaultAddress);
                    });
            address.setIsDefault(true);
        }
        
        return addressRepository.save(address);
    }
    
    @Transactional
    public void deleteAddress(Long id) {
        User user = getCurrentUser();
        UserAddress address = addressRepository.findByUserAndId(user, id)
                .orElseThrow(() -> new RuntimeException("地址不存在"));
        
        boolean wasDefault = address.getIsDefault();
        addressRepository.delete(address);
        
        // 如果删除的是默认地址，设置第一个地址为默认
        if (wasDefault) {
            List<UserAddress> addresses = addressRepository.findByUserOrderByIsDefaultDescCreatedAtDesc(user);
            if (!addresses.isEmpty()) {
                UserAddress firstAddress = addresses.get(0);
                firstAddress.setIsDefault(true);
                addressRepository.save(firstAddress);
            }
        }
    }
    
    public UserAddress getAddressById(Long id) {
        User user = getCurrentUser();
        return addressRepository.findByUserAndId(user, id)
                .orElseThrow(() -> new RuntimeException("地址不存在"));
    }
    
    @Transactional
    public UserAddress setDefaultAddress(Long id) {
        User user = getCurrentUser();
        UserAddress address = addressRepository.findByUserAndId(user, id)
                .orElseThrow(() -> new RuntimeException("地址不存在"));
        
        // 取消其他默认地址
        addressRepository.findByUserAndIsDefaultTrue(user)
                .ifPresent(defaultAddress -> {
                    defaultAddress.setIsDefault(false);
                    addressRepository.save(defaultAddress);
                });
        
        // 设置为默认地址
        address.setIsDefault(true);
        return addressRepository.save(address);
    }
    
    private User getCurrentUser() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        return userRepository.findByUsernameOrEmailOrMobile(username, username, username)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
    }
}
